package com.cilico.single.waterfall;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.os.AsyncTask;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.cilico.single.R;
import com.cilico.single.components.Component;
import com.cilico.single.components.CssStyle;
import com.cilico.single.shopcart.ShopCart;
import com.cilico.single.shopcart.ShopCartInfo;
import com.cilico.single.utils.PackageManagerAndroid;
import com.cilico.single.utils.Utils;
import com.cilico.single.view.BaseView;
import com.cilico.single.view.DetailView;
import com.cilico.single.view.FormLayout;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class Waterfall extends ListView implements Component{

	// 上下文
	public BaseView bv;
	// 控件名称
	public String name_;
	// 控件值
	public String value;
	// 当前控件，用于内部类
	private Waterfall self;
	// 开始刷新的状态
	private static final int REFRESH_STATE = 0x002;
	// 每页加载的条数
	public static final int PAGE_SIZE = 20;
	// 第一次加载数据标志
	public boolean page_first_ = true;
	/**加载更多，即向下翻页,累加*/
	public int PAGE_NEXT = 1;
	// 上一次请求返回的最后一条记录时间
	private String lastPageTime;
	// 适配器
	public WaterfallAdapter adapter;
	/**listview 数据结构*/
	private List<ItemBase> infoItems_;
	/**第一次加载的json数据*/
	private String json_;
	/**1:优惠信息列表。2：餐馆列表。3：餐馆菜品列表*/
	public String infoType_;
	/**加载更多的时候，url地址*/
	public String nextUrl_ = null;
	/**item详细信息报文请求url*/
	private String detailUrl_;
	// 最后的可视项索引
	private int visibleLastIndex = 0;
	public static int currentTab = 1;

	// 松开刷新状态
	private final static int RELEASE_To_REFRESH = 0;
	// 拉动刷新状态
	private final static int PULL_To_REFRESH = 1;
	// 正在刷新状态
	private final static int REFRESHING = 2;
	// 已经加载完毕状态
	private final static int DONE = 3;
	// 正在加载数据状态
	private final static int LOADING = 4;
	// 实际的padding的距离与界面上偏移距离的比例
	private final static int RATIO = 3;
	// 布局解析器
	private LayoutInflater inflater;
	// ListView头部的View
	private LinearLayout headView;
	// 提示信息“下拉刷新”的TextView
	private TextView tipsTextview;
	// 上次更新时间的TextView
	private TextView lastUpdatedTextView;
	// 箭头的图片
	private ImageView arrowImageView;
	// 刷新进度
	private ProgressBar progressBar;
	// 箭头向下动画
	private RotateAnimation animation;
	// 逆向箭头动画
	private RotateAnimation reverseAnimation;
	// 用于保证startY的值在一个完整的touch事件中只被记录一次
	private boolean isRecored;
	// 头部view内容的高度
	private int headContentHeight;
	/**视图的高度，以黄金分割比例系数为基准 */
	private int height_ = Utils.screenHeight_ * 64 / 100;
	/**视图的宽度*/
	private int width_;
	// 向下触屏事件时的手指起始y轴位置
	private int startY;
	// ListView第一项可见的索引
	private int visibleFirstIndex;
	// 刷新状态
	private int state;
	// 底部视图
	private View foot;
	// 加载更多布局
	private RelativeLayout loadMoreLayout;
	// 加载更多按钮
	private ImageView loadMoreBtn;
	// 是否反弹
	private boolean isBack;
	// 给外面预留的刷新的接口
	private OnRefreshListener refreshListener;
	// 是否刷新的标志位
	private boolean isRefreshable;
	// 样式
	public CssStyle cssStyle_; 
	/**ComBox与瀑布流联动的时候，ComBox选择的值要带给后台*/
	public int cmbNum_;
	/**搜索一个菜品，加载更多的时候带给后台*/
	public String moreText_;
	private ShopCart shopCart_;

	/**
	 * 构造
	 * @param context
	 * @param name 控件名字
	 * @param json 第一次初始化瀑布流的json数据
	 */
	public Waterfall(BaseView context,String name,String json) {
		super(context);
		self = this;
		bv = context;
		name_ = name;
		json_ = json;
		width_ = Utils.screenWidth_ - 30;//要缩放
		initHeadView(context);
		initFootView();
		loadView();
	}

	/**
	 * 头部初始化
	 * 
	 * @param context
	 *            上下文对象
	 */
	private void initHeadView(Context context) {
		inflater = LayoutInflater.from(context);
		// 获取ListView头部的view
		headView = (LinearLayout) inflater.inflate(R.layout.waterfall_mylistview_head, null);
		// 从头部的View获取箭头图片
		arrowImageView = (ImageView) headView.findViewById(R.id.head_arrowImageView);
		arrowImageView.setMinimumWidth(70);
		arrowImageView.setMinimumHeight(50);
		// 获取刷新进度条
		progressBar = (ProgressBar) headView.findViewById(R.id.head_progressBar);
		// 提示信息的TextView
		tipsTextview = (TextView) headView.findViewById(R.id.head_tipsTextView);
		// 最后刷新时间的TextView
		lastUpdatedTextView = (TextView) headView.findViewById(R.id.head_lastUpdatedTextView);
		measureView(headView);
		// 得到headView的原始高度
		headContentHeight = headView.getMeasuredHeight();
		// 设置内容的内部偏移量
		headView.setPadding(0, -1 * headContentHeight, 0, 0);
		headView.invalidate();

		// 加到ListView的头部view，ListView组件提供了两个很实用的功能，那就是可以在顶部和底部添加自定义的视图
		addHeaderView(headView, null, false);
		setOnScrollListener(new ClickScrool());

		// 箭头向下动画
		animation = new RotateAnimation(0, -180, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
		animation.setInterpolator(new LinearInterpolator());
		animation.setDuration(250);
		animation.setFillAfter(true);

		// 逆向箭头动画
		reverseAnimation = new RotateAnimation(-180, 0, RotateAnimation.RELATIVE_TO_SELF, 0.5f, RotateAnimation.RELATIVE_TO_SELF, 0.5f);
		reverseAnimation.setInterpolator(new LinearInterpolator());
		reverseAnimation.setDuration(200);
		reverseAnimation.setFillAfter(true);

		// 第一次加载默认完成的状态
		state = DONE;
		// 刷新标志位默认为false
		isRefreshable = false;
	}

	/**
	 * 初始化底部视图
	 */
	private void initFootView() {
		foot = inflater.inflate(R.layout.waterfall_listview_foot, null);
		loadMoreLayout = (RelativeLayout) foot.findViewById(R.id.listview_foot_layout);
		loadMoreBtn = (ImageView) foot.findViewById(R.id.listview_foot_more);
		loadMoreBtn.setOnClickListener(new Click());
		this.addFooterView(foot);
	}
	
	/**
	 * 视图装载及设置
	 */
	private void loadView() {
		this.setLayoutParams(new LinearLayout.LayoutParams(width_, height_));
		setCacheColorHint(0x00000000);
		setDivider(bv.getResources().getDrawable(R.drawable.waterfall_list_divider));
		setFocusable(true);
		infoItems_ = new ArrayList<ItemBase>();
		adapter = new WaterfallAdapter(bv, infoItems_, this);
		setAdapter(adapter);

		// 每个item的长按事件，弹出评论的view
		setOnItemLongClickListener(new ClickLong());

		// 每个item的点击事件，进入item的详细信息
		setOnItemClickListener(new ItemClick());

//		// 下拉刷新
//		setOnRefreshListener(new OnRefreshListener() {
//			public void OnRefresh() {
//				new RefreshTask().execute();
//			}
//		});
		
		// 加载更多按钮点击
		setOnLoadMoreListener(new OnLoadMoreListener() {
			public void OnLoadMore() {
				new LoadMoreTask().execute(new String[] {nextUrl_, lastPageTime });
			}
		});
		
		// 滚动监听,为了滚动到最后自动加载数据
		setOnMyScrollListener(new OnMyScrollListener() {

			public void onMyScrollStateChanged(AbsListView view, int scrollState) {
				// 数据集最后一项的索引
				int itemsLastIndex = adapter.getCount() - 1;
				// 最后一项引标:加上底部的loadMoreView项和头部下拉刷新的view
				int lastIndex = itemsLastIndex + 1 + 1;
				if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && visibleLastIndex == lastIndex) {
					// 在这里异步加载翻页数据
					new LoadMoreTask().execute(new String[] {nextUrl_, lastPageTime });
				}
			}

			public void OnMyScroll(AbsListView view, int firstVisiableItem, int visibleItemCount, int totalItemCount) {
				// 可见的最后一项
				visibleLastIndex = firstVisiableItem + visibleItemCount - 1; 
			}
		});

		new RefreshTask().execute();
	}
	
	/**
	 * 解析Json
	 * @author lvke
	 * Email: lvke@live.cn
	 * 2013-12-12下午4:28:34
	 * @param result
	 * @return
	 */
	private List<ItemBase> parseJson(String result){
		List<ItemBase> list = new ArrayList<ItemBase>();
		Gson gson = new Gson();
		if (result != null && infoType_ != null) {
			Type type = null;
			if (infoType_.trim().equals("1")) {
				type = new TypeToken<List<ItemInfo>>() {}.getType();
				list = gson.fromJson(result, type);
			} else if (infoType_.trim().equals("2")) {
				type = new TypeToken<List<ItemRestaurant>>() {}.getType();
				list = gson.fromJson(result, type);
			} else if (infoType_.trim().equals("3")) {
				type = new TypeToken<List<ItemMeal>>() {}.getType();
				list = gson.fromJson(result, type);
			}
		}
		
		return list;
	}


	/**
	 *  滑动事件回调
	 */
	private OnMyScrollListener myScrollListener;

	public interface OnMyScrollListener {
		public void OnMyScroll(AbsListView view, int firstVisiableItem, int visibleItemCount, int totalItemCount);

		public void onMyScrollStateChanged(AbsListView view, int scrollState);
	}

	public void setOnMyScrollListener(OnMyScrollListener myScrollListener) {
		this.myScrollListener = myScrollListener;
	}

	/**
	 * 触摸事件中断处理
	 */
	@Override
	public boolean onInterceptTouchEvent(MotionEvent ev) {
		switch (ev.getAction()) {
		case MotionEvent.ACTION_DOWN:
			// 当手指触到listview的时候，让父ScrollView交出ontouch权限，也就是让父scrollview停住不能滚动
			setParentScrollAble(false);
		case MotionEvent.ACTION_MOVE:
			break;
		case MotionEvent.ACTION_UP:
		case MotionEvent.ACTION_CANCEL:
			// 当手指松开时，让父ScrollView重新拿到onTouch权限
			setParentScrollAble(true);
			break;
		default:
			break;
		}
		return super.onInterceptTouchEvent(ev);
	}

	/**
	 * 是否把滚动事件交给父scrollview
	 * 
	 * @param flag
	 */
	private void setParentScrollAble(boolean flag) {
		// 这里的getParent()就是listview外面的那个父ScrollView
		this.getParent().requestDisallowInterceptTouchEvent(!flag);
	}

	/**
	 * 触摸事件
	 */
	public boolean onTouchEvent(MotionEvent event) {
		if (isRefreshable) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				if (visibleFirstIndex == 0 && !isRecored) {
					isRecored = true;
					startY = (int) event.getY();
				}
				break;
			case MotionEvent.ACTION_UP:
				if (state != REFRESHING && state != LOADING) {
					/* 下拉刷新 */
					if (state == PULL_To_REFRESH) {
						state = DONE;
						// 更新头部view
						changeHeaderViewByState(state);
					}
					/* 释放刷新 */
					if (state == RELEASE_To_REFRESH) {
						state = REFRESHING;
						changeHeaderViewByState(state);
						// 调用接口的方法，通知外面
						onRefresh();
					}
				}
				isRecored = false;
				isBack = false;
				break;
			case MotionEvent.ACTION_MOVE:
				int tempY = (int) event.getY();
				if (!isRecored && visibleFirstIndex == 0) {
					isRecored = true;
					startY = tempY;
				}
				/* 保证在设置padding的过程中，当前的位置一直是在head，否则如果当列表超出屏幕的话，当在上推的时候，列表会同时进行滚动 */
				if (state != REFRESHING && isRecored && state != LOADING) {
					if (state == RELEASE_To_REFRESH) {
						// 可以松手去刷新
						setSelection(0);
						if (((tempY - startY) / RATIO < headContentHeight) && (tempY - startY) > 0) {
							// 往上推到屏幕足够掩盖head但是还没有推到全部掩盖的地步
							state = PULL_To_REFRESH;
							changeHeaderViewByState(state);
						} else if (tempY - startY <= 0) {
							// 推到顶
							state = DONE;
							changeHeaderViewByState(state);
						} else {
							// 往下拉或者还没有上推到屏幕顶部掩盖head的地步
							// 不用进行特别的操作，只用更新paddingTop的值就行了
						}
					}
					if (state == PULL_To_REFRESH) {
						// 还没有到达显示松开刷新的时候,DONE或者是PULL_To_REFRESH状态
						setSelection(0);
						// 下拉到可以进入RELEASE_TO_REFRESH的状态
						if ((tempY - startY) / RATIO >= headContentHeight) {
							state = RELEASE_To_REFRESH;
							isBack = true;
							changeHeaderViewByState(state);
						}
						// 上推到顶
						else if (tempY - startY <= 0) {
							state = DONE;
							changeHeaderViewByState(state);
						}
					}
					/* done状态下 */
					if (state == DONE) {
						if (tempY - startY > 0) {
							state = PULL_To_REFRESH;
							changeHeaderViewByState(state);
						}
					}
					/* 更新headView的size */
					if (state == PULL_To_REFRESH) {
						headView.setPadding(0, -1 * headContentHeight + (tempY - startY) / RATIO, 0, 0);
					}
					// 更新headView的paddingTop
					if (state == RELEASE_To_REFRESH) {
						headView.setPadding(0, (tempY - startY) / RATIO - headContentHeight, 0, 0);
					}
				}
				break;
			}
		}
		return super.onTouchEvent(event);
	}

	// 当状态改变时候，调用该方法，以更新界面
	public void changeHeaderViewByState(int state) {
		switch (state) {
		/* 当前状态:松开刷新状态 */
		case RELEASE_To_REFRESH:
			arrowImageView.setVisibility(View.VISIBLE);// 显示箭头
			progressBar.setVisibility(View.GONE);// 移除进度条
			tipsTextview.setVisibility(View.VISIBLE);// 显示提示信息
			lastUpdatedTextView.setVisibility(View.VISIBLE);// 显示最后刷新时间
			arrowImageView.clearAnimation();// 先移除所有动画
			arrowImageView.startAnimation(animation);// 加载箭头向下动画
			tipsTextview.setText("释放立即刷新");
			break;
		/* 当前状态:下拉刷新状态 */
		case PULL_To_REFRESH:
			progressBar.setVisibility(View.GONE);// 移除进度条
			tipsTextview.setVisibility(View.VISIBLE);// 显示提示信息
			lastUpdatedTextView.setVisibility(View.VISIBLE);// 显示最后刷新时间
			arrowImageView.clearAnimation();// 先移除所有动画
			arrowImageView.setVisibility(View.VISIBLE);// 箭头图片可见
			// 如果是由RELEASE_To_REFRESH状态转变来的，就加载动画
			if (isBack) {
				isBack = false;
				arrowImageView.clearAnimation();
				arrowImageView.startAnimation(reverseAnimation);
				tipsTextview.setText("下拉可以刷新");
			} else {
				tipsTextview.setText("下拉可以刷新");
			}
			break;

		/* 当前状态,正在刷新... */
		case REFRESHING:
			headView.setPadding(0, 0, 0, 0);// 无内部偏移
			progressBar.setVisibility(View.VISIBLE);// 进度条可见
			arrowImageView.clearAnimation();// 先清除动画
			arrowImageView.setVisibility(View.GONE);// 再移除箭头动画
			tipsTextview.setText("正在刷新中...");// 提示信息变成正在刷新...
			lastUpdatedTextView.setVisibility(View.VISIBLE);// 最后刷新时间可见
			break;
		
		/* 当前状态,完成状态 */
		case DONE:
			headView.setPadding(0, -1 * headContentHeight, 0, 0);
			progressBar.setVisibility(View.GONE);
			arrowImageView.clearAnimation();
			arrowImageView.setImageResource(R.drawable.waterfall_wb_refresh_arrow);
			tipsTextview.setText("下拉可以刷新");
			lastUpdatedTextView.setVisibility(View.VISIBLE);
			break;
		}
	}

	// 刷新完成
	public void onRefreshComplete() {
		state = DONE;
		lastUpdatedTextView.setText("最近更新: 2018-09-01");
		changeHeaderViewByState(state);
	}

	/**
	 * 一个下拉刷新的监听接口
	 */
	public interface OnRefreshListener {
		public void OnRefresh();
	}

	// 监听方法
	public void setOnRefreshListener(OnRefreshListener refreshListener) {
		this.refreshListener = refreshListener;
		isRefreshable = true;
	}

	// 正在刷新
	private void onRefresh() {
		if (refreshListener != null) {
			refreshListener.OnRefresh();
		}
	}

	/**
	 * 此方法是“估计”headView的width以及height
	 * 
	 * @param child
	 *            传入进来的headView
	 */
	private void measureView(View child) {
		ViewGroup.LayoutParams p = child.getLayoutParams();
		if (p == null) {
			p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
		}
		int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
		int lpHeight = p.height;
		int childHeightSpec;
		if (lpHeight > 0) {
			childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
		} else {
			childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
		}
		child.measure(childWidthSpec, childHeightSpec);
	}

	private OnLoadMoreListener mLoadMoreListener; // 加载更多监听器
	private static int LVS_NORMAL = 0x001; // 普通状态
	private static int LVS_LOADING = 0x002; // 加载状态
	private static int LVS_OVER = 0x003; // 结束状态
	private int mLoadMoreState = LVS_NORMAL;

	public interface OnLoadMoreListener {
		public void OnLoadMore();
	}

	public void setOnLoadMoreListener(OnLoadMoreListener listener) {
		mLoadMoreListener = listener;
	}

	// flag 数据是否已全部加载完毕
	public void onLoadMoreComplete(boolean flag) {
		if (flag) {
			updateLoadMoreViewState(LVS_OVER);
		} else {
			updateLoadMoreViewState(LVS_NORMAL);
		}

	}

	// 更新footview视图
	public void updateLoadMoreViewState(int state) {
		switch (state) {
		case 0x001:
			loadMoreLayout.setVisibility(View.GONE);
			loadMoreBtn.setVisibility(View.VISIBLE);
			break;
		case 0x002:
			loadMoreLayout.setVisibility(View.VISIBLE);
			loadMoreBtn.setVisibility(View.GONE);
			break;
		case 0x003:
			loadMoreLayout.setVisibility(View.GONE);
			loadMoreBtn.setVisibility(View.VISIBLE);
			break;
		default:
			break;
		}

		mLoadMoreState = state;
	}

	public void removeFootView() {
		removeFooterView(foot);
	}

	// ListView添加Adapter方法
	public void setAdapter(BaseAdapter adapter) {
		lastUpdatedTextView.setText("最近更新: 2013-08-10");
		super.setAdapter(adapter);
	}

	/**
	 * 第一次加载和下拉刷新的异步任务
	 * 
	 * @author lv.xiangan
	 * 
	 */
	public class RefreshTask extends AsyncTask<Void, Void, String> {

		@Override
		protected void onPreExecute() {
			self.changeHeaderViewByState(REFRESH_STATE);
			self.updateLoadMoreViewState(REFRESH_STATE);
		}

		// 请求后台获取报文
		@Override
		protected String doInBackground(Void... params) {
			String result = getHomeMsg("", "", null);
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			if (result != null) {
				try {
					if (infoItems_ != null && infoItems_.size() > 0) {
						infoItems_.clear();//无论是第一次加载，还是下拉刷新
					}
					// 初步把报文切割成一个个item进行封装
					currentTab++;
					if (result != null && !result.trim().equals("")) {
						List<ItemBase> infos = parseJson(result);
						for (int i = 0; i < infos.size(); i++) {
							infoItems_.add(infos.get(i));
						}
					}
					// lastPageTime = itemsList.get(itemsList.size() - 1).getString("timestamp");// 得到最后一项的时间
					lastPageTime = "2000--000";
					adapter.notifyDataSetChanged();
					self.onRefreshComplete();
					self.onLoadMoreComplete(false);
				} catch (Exception e) {
					e.printStackTrace();
				}
			} else {
				self.onRefreshComplete();
				self.onLoadMoreComplete(false);
				Toast.makeText(bv, "获取数据失败,请重试", Toast.LENGTH_SHORT).show();
			}
		}
	}

	/**
	 * 加载更多的异步任务
	 * 
	 * @author lv.xiangan
	 * 
	 */
	public class LoadMoreTask extends AsyncTask<String, Void, String> {

		@Override
		protected void onPreExecute() {
			self.updateLoadMoreViewState(REFRESH_STATE);
		}

		// 请求后台获取报文
		@Override
		protected String doInBackground(String... params) {
			String result = getHomeMsg(params[0], params[1], null);
			return result;
		}

		@Override
		protected void onPostExecute(String result) {
			makeData(result,false);
		}
	}
	
	/**
	 * 处理json数据
	 * @author lvke
	 * Email: lvke@live.cn
	 * 2013-12-18下午5:18:22
	 * @param result
	 * @param again 是不是需要清空数据集合，重新加载
	 */
	public void makeData(final String result,final boolean again){

		bv.runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				if (again) {
					infoItems_.clear();
				}
				if (result != null) {
					if (result.trim().equals("[]")) {
						self.onLoadMoreComplete(false);
						Toast.makeText(bv, "没有数据了^_^", Toast.LENGTH_SHORT).show();
						adapter.notifyDataSetChanged();
					}else {
						try {
							List<ItemBase> itemInfos = parseJson(result);
							int size = infoItems_.size();
							// 如果长度太长，移除头20项，防止内存溢出
							if (size >= 60) {
								for (int i = 0; i < 20; ++i) {
									infoItems_.remove(i);
								}
								// 移除之后，重新获取一下item的总数
								size = infoItems_.size();
							}
							if (itemInfos != null && itemInfos.size() > 0) {
								int lenth = itemInfos.size();
								for (int i = 0; i < lenth; i++) {
									// 把报文添加到队列后面
									infoItems_.add(infoItems_.size(), itemInfos.get(i));
								}
							}
							
							// lastPageTime = items.get(items.size() - 1).getString("timestamp");// 得到最后一项的时间
							lastPageTime = "2000--000";
							adapter.notifyDataSetChanged();
							// 选择项÷
							self.setSelection(size);
							self.onLoadMoreComplete(false);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				} else {
					self.onLoadMoreComplete(false);
					Toast.makeText(bv, "获取数据失败(╯□╰)", Toast.LENGTH_SHORT).show();
				}
			}
		});
	
	}


	/**
	 * 获取报文接口，返回json字符串
	 * 
	 * @param pageflag
	 *            分页标识（0：第一页，1：向下翻页，2向上翻页）或者url
	 * @param pagetime
	 *            本页起始时间（第一页：填0，向上翻页：填上一次请求返回的第一条记录时间， 向下翻页：填上一次请求返回的最后一条记录时间）
	 * @param reqnum
	 *            每次请求记录的条数（1-70条）
	 * @param type
	 *            拉取类型 0x1 原创发表 0x2 转载 0x8 回复 0x10 空回 0x20 提及 0x40 点评 <br>
	 *            如需拉取多个类型请使用|，如(0x1|0x2)得到3，此时type=3即可，填零表示拉取所有类型
	 * @return
	 */
	public String getHomeMsg(String pageflag, String pagetime, String reqnum) {
		String msg = null;
		if (pageflag != null) {
			if (page_first_) {
				//第一次加载，返回xml中的json
				page_first_ = false;
				msg = json_;
			}else if(pageflag.trim().startsWith("http://")){
				//加载更多，再次请求后台，返回是json格式的数据
				PAGE_NEXT++;
				msg = bv.mid_.hm_.requstData(self,pageflag,null);
			}
		}
		return msg;
	}

	@Override
	public String getContentText() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setContentText(String text) {
		// TODO Auto-generated method stub

	}

	@Override
	public void shrinkWidth() {
	}

	@Override
	public void cleanText() {
		// TODO Auto-generated method stub

	}

	@Override
	public void mould() {
		CssStyle cs = cssStyle_;
		if (cs != null ) {
			if (cs.width_ != 0) {
				width_ = cs.width_;
			} else {
				width_ = Utils.screenWidth_ - Utils.getScaledValue(10);
			}
			if (cs.height_ != 0) {
				height_ = cs.height_;
			}
		} else {
			width_ = Utils.screenWidth_ - Utils.getScaledValue(10);
		}
	}

	@Override
	public void setCmpWidth(int width) {
		// TODO Auto-generated method stub
		width_ = width;
	}

	@Override
	public int getCmpWidth() {
		// TODO Auto-generated method stub
		return width_;
	}

	@Override
	public void setCmpHeidht(int height) {
		// TODO Auto-generated method stub
		height_ = height;
	}

	@Override
	public int getCmpHeight() {
		// TODO Auto-generated method stub
		return height_;
	}

	@Override
	public void setCssStyle(CssStyle style) {
		cssStyle_ = style;
	}

	@Override
	public View getCmpView() {
		// TODO Auto-generated method stub
		return this;
	}

	@Override
	public void setInTable(boolean inTable) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean isInTable() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public CssStyle getCssStyle() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void releaseResource(View view) {
		// TODO Auto-generated method stub

	}

	@Override
	public void setForm(FormLayout formLayout) {
		// TODO Auto-generated method stub

	}

	@Override
	public FormLayout getForm() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setEncrypt(String encrypt) {
		// TODO Auto-generated method stub

	}

	public String getNextUrl_() {
		return nextUrl_;
	}

	public void setNextUrl_(String nextUrl_) {
		this.nextUrl_ = nextUrl_;
	}

	public String getInfoType_() {
		return infoType_;
	}

	public void setInfoType_(String infoType_) {
		this.infoType_ = infoType_;
	}

	public String getDetailUrl_() {
		return detailUrl_;
	}

	public void setDetailUrl_(String detailUrl_) {
		this.detailUrl_ = detailUrl_;
	}
	
	class Click implements OnClickListener{

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch (v.getId()) {
			case R.id.listview_foot_more: {
				if (mLoadMoreListener != null && mLoadMoreState == LVS_NORMAL) {
					updateLoadMoreViewState(LVS_LOADING);
					mLoadMoreListener.OnLoadMore();
				}
			}
				break;
			}
		}
		
	}
	
	class ClickLong implements OnItemLongClickListener{

		@Override
		public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
				int arg2, long arg3) {
			// TODO Auto-generated method stub
			return false;
		}

		
	}
	
	class ClickScrool implements OnScrollListener{

		public void onScroll(AbsListView view, int firstVisiableItem, int visibleItemCount, int totalItemCount) {
			visibleFirstIndex = firstVisiableItem;// ListView第一个索引值为ListView数据中第一个可见项
			if (myScrollListener != null)
				myScrollListener.OnMyScroll(view, firstVisiableItem, visibleItemCount, totalItemCount);// 回调
		}

		public void onScrollStateChanged(AbsListView view, int scrollState) {
			if (myScrollListener != null)
				myScrollListener.onMyScrollStateChanged(view, scrollState);
		}
		
	}
	
	class ItemClick implements OnItemClickListener{

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
			String infoId = null;
			if (infoType_ != null && infoItems_ != null && infoItems_.size() > 0
					&& arg2 > 0 && arg2 < infoItems_.size() + 1) {//保障点击的不是头部和底部
				if (infoType_.equals("1")) {
					ItemInfo itemInfo = (ItemInfo) infoItems_.get(arg2 - 1);// 去掉头部
					infoId = itemInfo.getId();
				} else if (infoType_.equals("2")) {
					ItemRestaurant infoRestaurant = (ItemRestaurant) infoItems_.get(arg2 - 1);
					infoId = infoRestaurant.getId();
					//存储当前ID
					BaseView.mid_.pm_.SAVEPROPERTYDB_.save(PackageManagerAndroid.ID_RESTAURANT, infoId);
				}  else if (infoType_.equals("3")) {
					ItemMeal itemmeal = (ItemMeal) infoItems_.get(arg2 - 1);
					if (!itemmeal.getIsSell().equals("1")) {
						//已售完的菜品不可以点击
						infoId = itemmeal.getId();
						ImageView img = (ImageView)arg1.findViewById(R.id.item_book);
						doMeal(arg1, itemmeal, img);
					}else {
						Toast.makeText(bv, "菜品已售完!", Toast.LENGTH_LONG).show();
					}
				}
				
				if (infoId != null && !infoId.equals("") && null != bv && bv instanceof DetailView) {
					if (detailUrl_ != null) {
						if (detailUrl_.indexOf("?") == -1)
							detailUrl_ = detailUrl_.concat("?");
						if (detailUrl_.endsWith("?")) {
							detailUrl_ = detailUrl_.concat("id=" + infoId);
						}
						DetailView mbv = (DetailView) bv;
						mbv.dealWithLink(detailUrl_, mbv, false);
					}
				}
				
			}
		}
	}
	
	private void doMeal(View view,final ItemMeal itemMeal,final ImageView img){

		boolean hasChecked = false;
		if (null != ShopCart.order.get(itemMeal.getId())) {
			hasChecked = true;
		}
		if (null != shopCart_) {
			/* 当取消勾选 */
			if (hasChecked) {
				img.setImageResource(R.drawable.unchecked);
				// 在列表删除已点
				bv.runOnUiThread(new Runnable() {

					@Override
					public void run() {
						// 小球减一
						shopCart_.cancelItem();
						// 删除缓存
						ShopCart.order.remove(itemMeal.getId());
					}
				});
			} else {
				/* 当勾选时 */
				img.setImageResource(R.drawable.checked);

				bv.runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						/* 为防止多次连击小球数字不对的问题出现，先判断该id是否已放进缓存 */
						boolean cached = false;
						Iterator iter = ShopCart.order.entrySet().iterator();
						while (iter.hasNext()) {
							Map.Entry entry = (Map.Entry) iter.next();
							String key = (String) entry.getKey();
							if (null != key && key.equals(itemMeal.getId())) {
								cached = true;
								break;
							}
						}
						if (!cached) {
							shopCart_.buyNum++;
							int[] start_location = new int[2];// 一个整型数组，用来存储按钮的在屏幕的X、Y坐标
							img.getLocationInWindow(start_location);// 这是获取购买按钮的在屏幕的X、Y坐标（这也是动画开始的坐标）
							shopCart_.rollBall = new ImageView(bv);// rollBall是动画的图片:一个小球
							shopCart_.rollBall.setImageResource(R.drawable.shopping_sign);// 设置rollBall的图片
							shopCart_.setAnimination(shopCart_.rollBall, start_location);// 开始执行动画
							
							// 把菜品id作为关键字保存，避免出现id不对的问题
							ShopCart.order.put(itemMeal.getId(), itemMeal);
							// 把当前item关键数据保存，用于本地listview显示
							ShopCartInfo cartInfo = new ShopCartInfo(
									itemMeal.getRestaurantId(),
									itemMeal.getId(),
									itemMeal.getMenuName(),
									itemMeal.getPrice(),
									"1"); // 默认数量为一份
							cartInfo.setSpecial_(itemMeal.getSpecial());
							// 把当前item数据生成json并保存
							List <ItemBase> ls = new ArrayList <ItemBase>();
							ls.add(itemMeal);
							String json = Utils.makeJson(ls, "3");
							String oldShowValue = BaseView.mid_.pm_.SAVEPROPERTYDB_.get(PackageManagerAndroid.SHOPCART_DB);
							String oldRealValue = BaseView.mid_.pm_.SAVEPROPERTYDB_.get(PackageManagerAndroid.SHOPCART_REAL_DB);
							if (TextUtils.isEmpty(oldShowValue)) {
								BaseView.mid_.pm_.SAVEPROPERTYDB_.save(PackageManagerAndroid.SHOPCART_DB, cartInfo.toString());
								BaseView.mid_.pm_.SAVEPROPERTYDB_.save(PackageManagerAndroid.SHOPCART_REAL_DB, json);
							} else {
								BaseView.mid_.pm_.SAVEPROPERTYDB_.save(PackageManagerAndroid.SHOPCART_DB, oldShowValue + "@" + cartInfo.toString());
								BaseView.mid_.pm_.SAVEPROPERTYDB_.save(PackageManagerAndroid.SHOPCART_REAL_DB, oldRealValue + "@" + json);
							}
						}
						
						
					}
				});
			}
		}
		
	}

	public ShopCart getShopCart() {
		return shopCart_;
	}
	
	public void setShopCart(ShopCart shopCart) {
		shopCart_ = shopCart;
	}
}


